package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.mapper.PaymentMapper;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @Description:
 * @author: JC
 * @date: 2021/11/13 16:30
 */
@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private PaymentService paymentService;

    @Override
    public String createAliPay(Long orderId) throws AlipayApiException {

        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);

        String orderStatus = orderInfo.getOrderStatus();
        // 如果取消订单了，不能生成二维码
        if(StringUtils.equals(orderStatus,PaymentStatus.CLOSED.name())){
            throw new GmallException("支付已关闭",1234);
        }

        if(StringUtils.equals(orderStatus,PaymentStatus.PAID.name())){
            throw new GmallException("已支付完成了",1234);
        }

        // 生成二维码 ，保存交易记录
        // 支付默认支付宝支付
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        Gson gson = new Gson();
        String s = gson.toJson(orderInfo);
        // 保存交易记录
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
        // 生产二维码
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        // 同步回调
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        // 异步回调
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);//在公共参数中设置回跳和通知地址
        // 参数
        // 声明一个map 集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",orderInfo.getTotalAmount());
        map.put("subject","test");

        alipayRequest.setBizContent(JSON.toJSONString(map));

        return alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单;
    }
}
